package com.laikan.reader.bookfriend.activity;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.OvershootInterpolator;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookreader.activity.BookDesActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.ShareReadGiftsAdapter;
import com.laikan.reader.core.adapter.ShareReadRuleAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.ShareBookBean;
import com.laikan.reader.core.bean.ShareReadBean;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.utils.ShareSdkReadBookShare;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @author wx
 * @version 创建时间：2016-1-25 上午9:37:04
 * @E-mail wx1343571153@163.com
 * @category 我的享读
 */

public class MyShareRead extends BasicActivity implements OnClickListener {

    protected final int RECEIVE_GIFTS_AFTER = 2;
    private final int SET_VIEW = 1;
    private WindowManager wm;
    private RedPackPopupWindow window;
    private com.laikan.reader.core.view.MyScrollView sv_share_read;
    private ViewPager vp_guide;
    private RelativeLayout rl_top;
    private RelativeLayout rl_no_gifts;        // 无享读礼包提示
    private LinearLayout ll_share_read_gifts; // 我的享读礼包列表
    private LinearLayout ll_share_read;          // 分享好书列表
    private LinearLayout ll_share_read_content;
    private LinearLayout ll_body;
    private LinearLayout ll_share_read_rule;
    private RelativeLayout title; //标题
    private ImageView back_tv; //返回键
    private TextView title_tv; //标题文本

    private com.facebook.drawee.view.SimpleDraweeView iv_headPortrait;
    private TextView tv_name;
    private TextView tv_coupons;
    private ListView lv_share_read_rule;
    private ListView lv_share_read;
    private SimpleDraweeView iv_book01;
    private SimpleDraweeView iv_book02;
    private SimpleDraweeView iv_book03;
    private TextView tv_book01;
    private TextView tv_book02;
    private TextView tv_book03;
    private TextView tv_more; // 查看更多
    private TextView tv_start; // 引导页进入按钮
    private String[] mData;
    private ShareReadRuleAdapter srrAdapter;
    private ShareReadGiftsAdapter srgAdapter;
    private ViewPagerAdapter vpAdapter;
    private int scrWidth; // 屏幕宽
    private int scrHeight; // 屏幕高
    private int statusBarHeight; // 状态栏高度
    private int originHeight;
    private int maxTopHeight;
    private int upDataOfHeight;
    /**
     * 屏幕宽度的4分之一
     */
    private int quarter = 0;
    // public float imgRatio = 7.0f / 4;
    private float imgRatio = 400f / 1136f;
    // private boolean isScrollBan = false; // false:不禁止滚动 true:禁止滚动
    private int marginTop = 20;
    private float density;
    private ArrayList<ShareBookBean> bookList;      // 我的享读书籍
    private ArrayList<ShareReadBean> shareReadList; // 享读礼包
    private ShareBookBean shareBook01;
    private ShareBookBean shareBook02;
    private ShareBookBean shareBook03;
    private String userIcon;
    private String totalQuan;
    private String userName;
    private int end = 10; // 开始显示的礼包个数
    private int addItem = 10; // 查看更多添加显示的礼包个数

    Drawable drawable_back_tv;
    private View top_line;
    private int mHeight;
    private RelativeLayout back_layout;

    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SET_VIEW: // 初始化控件值
                    setView();

                    break;
                case RECEIVE_GIFTS_AFTER:
                    ShareReadBean b = (ShareReadBean)msg.obj;
                    upDataView(b);

                    break;
            }
        }
    };

    /**
     * 领取礼包后更新控件
     *
     * @date 2016-1-28 下午3:57:33
     * @author yjh
     */
    protected void upDataView(ShareReadBean b) {
        // 打开红包窗口
        window = new RedPackPopupWindow(MyShareRead.this, b);
        window.showAtLocation(sv_share_read, Gravity.CENTER, 0, 0);

        srgAdapter.notifyDataSetChanged();
        String format = String.format(getString(R.string.cumulative_coupons), totalQuan);
        tv_coupons.setText(format);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.my_share_read);
        sv_share_read = (com.laikan.reader.core.view.MyScrollView)findViewById(R.id.sv_share_read);
        rl_top = (RelativeLayout)findViewById(R.id.laikan_title);
        rl_no_gifts = (RelativeLayout)findViewById(R.id.rl_no_gifts);
        ll_share_read_gifts = (LinearLayout)findViewById(R.id.ll_share_read_gifts);
        ll_share_read_content = (LinearLayout)findViewById(R.id.ll_share_read_content);
        ll_body = (LinearLayout)findViewById(R.id.ll_body);
        ll_share_read = (LinearLayout)findViewById(R.id.ll_share_read);
        ll_share_read_rule = (LinearLayout)findViewById(R.id.ll_share_read_rule);
        title = (RelativeLayout)findViewById(R.id.rl_title);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        title_tv = (TextView)findViewById(R.id.tv_title);
        top_line = findViewById(R.id.top_divider);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        iv_headPortrait = (com.facebook.drawee.view.SimpleDraweeView)findViewById(R.id.iv_headPortrait);
        tv_name = (TextView)findViewById(R.id.top_book_name);
        tv_coupons = (TextView)findViewById(R.id.tv_coupons);
        lv_share_read_rule = (ListView)findViewById(R.id.lv_share_read_rule);
        lv_share_read = (ListView)findViewById(R.id.lv_share_read);
        iv_book01 = (SimpleDraweeView)findViewById(R.id.iv_book01);
        iv_book02 = (SimpleDraweeView)findViewById(R.id.iv_book02);
        iv_book03 = (SimpleDraweeView)findViewById(R.id.iv_book03);
        tv_book01 = (TextView)findViewById(R.id.tv_book01);
        tv_book02 = (TextView)findViewById(R.id.tv_book02);
        tv_book03 = (TextView)findViewById(R.id.tv_book03);
        tv_more = (TextView)findViewById(R.id.tv_more);
        vp_guide = (ViewPager)findViewById(R.id.vp_guide);

        String user_icon = SPUtil.getString("user_icon", "");
        String user_name = SPUtil.getString("user_name", "");
        // 1.头像
        iv_headPortrait.setImageURI(Uri.parse(user_icon));
        // 2.用户名
        tv_name.setText(user_name);

    }

    private void checkShowGuidePage() {
        Rect frame = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        statusBarHeight = frame.top;
        if (SPUtil.getBoolean("isFirstShareRed", true)) {
            ll_share_read_content.setVisibility(View.INVISIBLE);
            title.setBackgroundResource(R.color.C_FFFFFF);
            title_tv.setTextColor(Color.parseColor("#333333"));
            drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
            back_tv.setImageDrawable(drawable_back_tv);
            initGuide();
        }
    }

    @Override
    protected void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        // 设置头部高度
        wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        density = mContext.getApplicationContext().getResources().getDisplayMetrics().density;
        marginTop *= density;
        scrWidth = wm.getDefaultDisplay().getWidth();
        scrHeight = wm.getDefaultDisplay().getHeight();

        quarter = scrWidth / 4;
        // int height = (int) (quarter * imgRatio) + marginTop;

        mHeight = (int)(imgRatio * scrHeight);
        rl_top.setLayoutParams(new LinearLayout.LayoutParams(scrWidth, mHeight));

        // 享读规则
        mData = getResources().getStringArray(R.array.shareReadRule);
        srrAdapter = new ShareReadRuleAdapter(mContext);
        srrAdapter.setDatas(new ArrayList<String>(Arrays.asList(mData)));
        lv_share_read_rule.setAdapter(srrAdapter);
        // 1.去掉分割线
        lv_share_read_rule.setDivider(null);
        // 2.去掉选中背景
        lv_share_read_rule.setSelector(android.R.color.transparent);

        shareReadList = new ArrayList<ShareReadBean>();
        srgAdapter = new ShareReadGiftsAdapter(mContext);

        getData();
    }

    private void setView() {
        ll_body.setVisibility(View.VISIBLE);
        // 1.头像
        iv_headPortrait.setImageURI(Uri.parse(userIcon));

        // 2.累计领取阅读券
        String format = String.format(getString(R.string.cumulative_coupons), totalQuan);
        tv_coupons.setText(format);

        // 3.用户名
        tv_name.setText(userName);

        // 4.分享好书领礼包(我的享读书籍)
        if (bookList.size() > 0) {
            shareBook01 = bookList.get(0);
            shareBook02 = bookList.get(1);
            shareBook03 = bookList.get(2);
            if (shareBook01 != null) {
                iv_book01.setImageURI(Uri.parse(shareBook01.getBookIcon()));
            }
            if (shareBook02 != null) {
                iv_book02.setImageURI(Uri.parse(shareBook02.getBookIcon()));
            }
            if (shareBook03 != null) {
                iv_book03.setImageURI(Uri.parse(shareBook03.getBookIcon()));
            }
        }

        // 5.显示享读礼包或分享好书
        ArrayList<ShareReadBean> subList = new ArrayList<ShareReadBean>();
        if (shareReadList.size() > end) {
            subList = new ArrayList<ShareReadBean>(shareReadList.subList(0, end));
            tv_more.setVisibility(View.VISIBLE);
        }else {
            subList = shareReadList;
        }
        srgAdapter.setDatas(subList);
        lv_share_read.setAdapter(srgAdapter);

        if (shareReadList.size() > 0) {
            lv_share_read.setVisibility(View.VISIBLE);
            rl_no_gifts.setVisibility(View.GONE);
        }else {
            lv_share_read.setVisibility(View.GONE);
            rl_no_gifts.setVisibility(View.VISIBLE);
        }
        // 6.显示分享规则
        ll_share_read_rule.setVisibility(View.VISIBLE);

    }

    private void getData() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                KLog.d("MySharedRead.java", "result json: " + httpResponse.responseContent.toString());
                BaseDataBean<BaseListDataBean<ShareBookBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<ShareBookBean>>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                }catch (JsonSyntaxException e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }

                try {
                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            if (result.getError_no().equals("201")) {
                                // 未登录.
                                SPUtil.putString("user_id", "0");
                                SPUtil.putString("token", "");
                                SPUtil.putBoolean("login_laikan_setting", false);
                                startActivity(new Intent(mContext, LoginActivity.class));
                            }
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            // 已登录
                            bookList = result.getData().getBookList();
                            shareReadList = result.getData().getShareReadList();
                            userIcon = result.getData().getUserIcon();
                            userName = result.getData().getUserName();
                            totalQuan = result.getData().getTotalQuan();
                            handler.sendEmptyMessage(SET_VIEW);
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    }

                }catch (Exception e) {
                    e.getMessage();
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ll_body.setVisibility(View.VISIBLE);
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_share_read);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_share_read, map, null, null, requestListener);
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        iv_book01.setOnClickListener(this);
        iv_book02.setOnClickListener(this);
        iv_book03.setOnClickListener(this);
        tv_book01.setOnClickListener(this);
        tv_book02.setOnClickListener(this);
        tv_book03.setOnClickListener(this);
        tv_more.setOnClickListener(this);

        lv_share_read.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ShareReadBean b = shareReadList.get(position);
                if (!b.isReceived()) {
                    receiveGifts(shareReadList.get(position));
                }
            }

        });

        final int height = 100;
        sv_share_read.setOnScrollListener(new com.laikan.reader.core.view.MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(com.laikan.reader.core.view.MyScrollView myScrollView, int l, int scrollY, int oldl, int oldy) {
                int color = 0;
                if (scrollY < height) {
                    color = Color.argb(0, 0, 0, 0);
                    title.setBackgroundColor(color);
                    back_tv.setImageResource(R.drawable.lk_back_small);
                    title_tv.setTextColor(Color.parseColor("#FFFFFF"));
                    top_line.setVisibility(View.GONE);
                }else {
                    if (scrollY > height) {
                        color = Color.argb(255, 255, 255, 255);
                        title.setBackgroundColor(color);
                        back_tv.setImageDrawable(drawable_back_tv);
                        title_tv.setTextColor(Color.parseColor("#333333"));
                        top_line.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        rl_top.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                originHeight = rl_top.getHeight();
                maxTopHeight = originHeight + originHeight / 3;
                upDataOfHeight = originHeight + originHeight / 4;
                rl_top.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                KLog.e("384 originHeight = " + originHeight);
            }
        });

        // deltaY : Y轴的瞬时变化量, 向下拉时是负值，向上拉是正值
        // scrollY ： Y轴的滚动量.
        // scrollRangeY : Y轴的滚动范围。
        // maxOverScrollY: Y轴最大滚动位置
        // isTouchEvent： 是否是由手指触摸超出的，是则为true, 如果是惯性,则为false
        sv_share_read.setmOverScrollBy(new com.laikan.reader.core.view.MyScrollView.MOverScrollBy() {
            @Override
            public void mOverScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
                if (isTouchEvent && 0 >= scrollY && 0 > deltaY) {
                    // 手指向下拉ScrollView, 并且ScrollView顶部到头了
                    int newHeight = (int)(rl_top.getHeight() + Math.abs(deltaY) / 2.0f);
                    /*if (newHeight <= maxTopHeight) {
                        // 给新的高度赋值
                        rl_top.getLayoutParams().height = newHeight;
                        rl_top.requestLayout();
                    }*/
                    // 给新的高度赋值
                    rl_top.getLayoutParams().height = newHeight;
                    rl_top.requestLayout();
                    //                    KLog.e("402-1 deltaY = " + deltaY + "\t scrollY = " + scrollY + "\t scrollRangeY = " + scrollRangeY + "\t maxOverScrollY = " + maxOverScrollY);
                }else if (isTouchEvent && deltaY > 0) {
                    // 手指向上滑scrollView
                    int newHeight = (int)(rl_top.getHeight() - Math.abs(deltaY) / 2.0f);
                    if (newHeight >= originHeight) {
                        // 给新的高度赋值
                        rl_top.getLayoutParams().height = newHeight;
                        rl_top.requestLayout();
                    }
                }
            }
        });

        sv_share_read.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        sv_share_read.setMove(true);
                        KLog.e("486 move ");
                        break;
                    case MotionEvent.ACTION_UP:

                        final int startValue = rl_top.getHeight();
                        ValueAnimator mAnim = ValueAnimator.ofInt(1);
                        mAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                float percent = valueAnimator.getAnimatedFraction();
                                // KLog.e("445 percent = " + percent);
                                Integer height = evaluate(percent, startValue, originHeight);
                                // 给新的高度赋值
                                rl_top.getLayoutParams().height = height;
                                rl_top.requestLayout();
                                if (percent == 1.0f && upDataOfHeight < startValue) {
                                    // getData();
                                    KLog.e("433   刷新数据......");
                                }
                            }
                        });
                        mAnim.setInterpolator(new OvershootInterpolator(0));
                        mAnim.setDuration(500);
                        mAnim.start();

                        break;
                }
                return false;
            }
        });

        /*sv_share_read.setmOnTouchEvent(new MyScrollView.MOnTouchEvent() {
            @Override
            public void mOnTouchEvent(MotionEvent ev) {
                switch(ev.getAction()){
                    case MotionEvent.ACTION_UP:

                        final int startValue = rl_top.getHeight();
                        ValueAnimator mAnim = ValueAnimator.ofInt(1);
                        mAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                float percent = valueAnimator.getAnimatedFraction();
                                KLog.e("445 percent = " + percent);
                                Integer height = evaluate(percent, startValue, originHeight);
                                // 给新的高度赋值
                                rl_top.getLayoutParams().height = height;
                                rl_top.requestLayout();
                            }
                        });
                        mAnim.setInterpolator(new OvershootInterpolator(4));
                        mAnim.setDuration(500);
                        mAnim.start();
                        break;
                }
            }
        });*/
        checkShowGuidePage();
    }

    private Integer evaluate(float fraction, Integer startValue, Integer endValue) {
        int startInt = startValue;
        return (int)(startInt + fraction * (endValue - startInt));
    }

    /**
     * 领取礼包
     *
     * @param b
     *
     * @date 2016-1-28 下午2:14:55
     * @author yjh
     */
    protected void receiveGifts(final ShareReadBean b) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("mobile", b.getShareReadId());

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(httpResponse.responseContent);
                    String result = jsonObject.getString("result");
                    String error_no = jsonObject.getString("error_no");
                    String error_msg = jsonObject.getString("error_msg");

                    if (!Constants.RESULT_OK.equals(result)) {
                        if (error_no.equals("201")) {
                            // 未登录.
                            SPUtil.putString("user_id", "0");
                            SPUtil.putString("token", "");
                            SPUtil.putBoolean("login_laikan_setting", false);
                            startActivity(new Intent(mContext, LoginActivity.class));
                        }
                        ToastMgr.showShortToast(error_msg);
                    }else {
                        // 已登录
                        b.setReceived(true);
                        Integer upTotalQuan = Integer.valueOf(totalQuan) + Integer.valueOf(b.getShareReadSendQuan());
                        totalQuan = upTotalQuan + "";
                        Message msg = Message.obtain();
                        msg.obj = b;
                        msg.what = RECEIVE_GIFTS_AFTER;
                        handler.sendMessage(msg);
                        ToastMgr.showShortToast(R.string.receive_success);

                    }

                }catch (Exception e) {
                    e.printStackTrace();
                }
                KLog.e("344 json = " + httpResponse.responseContent);
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {

                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "share/get/senderquan");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL2() + "share/get/senderquan", map, null, null, requestListener);

    }

    @Override
    public void onClick(View v) {

        try {
            switch (v.getId()) {
                case R.id.iv_book01:
                    opneBookDes(shareBook01.getBookId());

                    break;
                case R.id.iv_book02:
                    opneBookDes(shareBook02.getBookId());

                    break;
                case R.id.iv_book03:
                    opneBookDes(shareBook03.getBookId());

                    break;
                case R.id.tv_book01:
                    MobclickAgent.onEvent(mContext, "bookrack_share");
                    ShareSdkReadBookShare.readBookShare(shareBook01.getBookId(), null, MyShareRead.this);
                    break;
                case R.id.tv_book02:
                    MobclickAgent.onEvent(mContext, "bookrack_share");
                    ShareSdkReadBookShare.readBookShare(shareBook02.getBookId(), null, MyShareRead.this);
                    break;
                case R.id.tv_book03:
                    MobclickAgent.onEvent(mContext, "bookrack_share");
                    ShareSdkReadBookShare.readBookShare(shareBook03.getBookId(), null, MyShareRead.this);
                    break;
                case R.id.tv_more:
                    if (end == shareReadList.size()) {
                        return;
                    }
                    int start = end;
                    end = end + addItem;
                    ArrayList<ShareReadBean> subList = new ArrayList<ShareReadBean>();
                    if (shareReadList.size() > end) {
                        subList = new ArrayList<ShareReadBean>(shareReadList.subList(start, end));
                    }else {
                        subList = new ArrayList<ShareReadBean>(shareReadList.subList(start, shareReadList.size()));
                        end = shareReadList.size();
                        tv_more.setVisibility(View.GONE);
                    }
                    srgAdapter.addDatas(subList);
                    break;

                case R.id.tv_start:
                    // isScrollBan = false;
                    title.setBackgroundResource(R.color.translucent);
                    title_tv.setTextColor(Color.parseColor("#FFFFFF"));
                    back_tv.setImageResource(R.drawable.lk_back_small);
                    vp_guide.setVisibility(View.GONE);
                    ll_share_read_content.setVisibility(View.VISIBLE);
                    SPUtil.putBoolean("isFirstShareRed", false);
                    break;
                case R.id.back_layout:
                    finish();
                    break;
                default:
                    break;
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

    }

    /**
     * 初始化引导
     *
     * @date 2016-1-28 上午11:21:38
     * @author yjh
     */
    public void initGuide() {

        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        title.measure(w, h);
        int height = title.getMeasuredHeight(); // 顶部标题栏高度
        // RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(scrWidth, scrHeight - height - statusBarHeight/2);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.BELOW, R.id.rl_title);
        vp_guide.setLayoutParams(lp);

        ImageView iv01 = new ImageView(mContext);
        ImageView iv02 = new ImageView(mContext);
        iv01.setScaleType(ScaleType.CENTER_CROP);
        iv02.setScaleType(ScaleType.CENTER_CROP);
        iv01.setBackgroundResource(R.drawable.share_read_01);
        iv02.setBackgroundResource(R.drawable.share_read_02);
        View view03 = View.inflate(mContext, R.layout.share_read03, null);
        tv_start = (TextView)view03.findViewById(R.id.tv_start);
        tv_start.setOnClickListener(this);

        ArrayList<View> views = new ArrayList<View>();
        views.add(iv01);
        views.add(iv02);
        views.add(view03);
        vpAdapter = new ViewPagerAdapter(views);
        vp_guide.setAdapter(vpAdapter);
        // 禁止滚动
        // isScrollBan = true;
        // 将背景在此设置,避免该控件测量有误差
        //        ctl_title.setBackgroundResource(R.drawable.over_bg);
        title.setBackgroundResource(R.color.C_FFFFFF);
        title_tv.setTextColor(Color.parseColor("#333333"));
        back_tv.setImageDrawable(drawable_back_tv);
    }

    /**
     * 进入书籍详情页
     *
     * @param bookId
     *
     * @date 2016-1-27 上午10:46:57
     * @author yjh
     */
    public void opneBookDes(String bookId) {
        Intent intent = new Intent();
        intent.setClass(mContext, BookDesActivity.class);
        intent.putExtra("bookId", bookId);
        startActivity(intent);
    }

    /**
     * @author 功能描述：ViewPager适配器，用来绑定数据和view
     */
    public class ViewPagerAdapter extends PagerAdapter {

        //界面列表
        private ArrayList<View> views;

        public ViewPagerAdapter(ArrayList<View> views) {
            this.views = views;
        }

        /**
         * 获得当前界面数
         */
        @Override
        public int getCount() {
            if (views != null) {
                return views.size();
            }
            return 0;
        }

        /**
         * 初始化position位置的界面
         */
        @Override
        public Object instantiateItem(View view, int position) {

            ((ViewPager)view).addView(views.get(position), 0);

            return views.get(position);
        }

        /**
         * 判断是否由对象生成界面
         */
        @Override
        public boolean isViewFromObject(View view, Object arg1) {
            return (view == arg1);
        }

        /**
         * 销毁position位置的界面
         */
        @Override
        public void destroyItem(View view, int position, Object arg2) {
            ((ViewPager)view).removeView(views.get(position));

        }
    }

}
